const router = require('koa-router')();
const UserController = require('../controller/user')

const jwt = require('jsonwebtoken')
const { key } = require('../config')

// 登陆授权中间件
const auth = async (ctx, next) => {
  // token前端一般通过header带过来；
  try {
    let { authorization } = ctx.request.header;
    console.log('authorization: ', authorization)
    let data = jwt.verify(authorization, key)
    ctx.state.user = data; // 命名空间。保存账号密码方便其他地方使用
    await next()
  } catch (e) {
    ctx.body = { status: 401, msg: '用户名密码错误' }
  }
}


router.prefix('/api')
// 登陆
router.post('/login', UserController.login)
// 注册 
router.post('/register', UserController.register)
// 操作 blogs
router.post('/add', auth, UserController.add)
router.delete('/delete', auth, UserController.delete)
router.put('/update', auth, UserController.update)

router.get('/findAll', UserController.findAll)
router.get('/page', auth, UserController.page)
router.get('/search', auth, UserController.search)


module.exports = router;
